package com.jic.market.impl.rest.discount;

import com.jic.market.common.exception.MarketErrorCodeEnum;
import com.jic.market.common.exception.MarketException;
import com.jic.market.common.util.Money;
import com.jic.market.entity.*;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.coupon.CouponDetail;
import com.jic.market.enums.*;
import com.jic.market.impl.rest.discount.model.ConditionDiscountModel;
import com.jic.market.impl.rest.discount.model.DiscountOrderModel;
import com.jic.market.impl.rest.discount.model.GoodsDetailModel;
import com.jic.market.impl.rest.discount.model.ShareModel;
import com.jic.market.impl.rest.discount.processor.AbstractConditionDiscountProcessor;
import com.jic.market.mapper.*;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.coupon.CouponDetailMapper;
import com.jic.market.mapper.coupon.CouponGoodsMapper;
import com.jic.market.request.rest.discount.ConditionDiscountRequest;
import com.jic.market.request.rest.discount.DiscountSubOrderRequest;
import com.jic.market.request.rest.discount.GoodsDetailRequest;
import com.jic.market.request.rest.discount.PromotionGoods;
import com.jic.market.response.rest.coupon.QueryCouponPersonResponse;
import com.jic.market.response.rest.discount.GiftDetail;
import com.jic.market.service.rest.discount.DiscountModelService;
import com.jic.market.service.rest.discount.DiscountProcesserService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author yinhaijun
 * @date: 2020/4/27
 */
@Service
public class DiscountModelServiceImpl implements DiscountModelService {

    @Resource
    private ProductListApi productListApi;
    @Autowired
    private CouponGoodsMapper couponGoodsMapper;
    @Autowired
    private DiscountOrderDetailMapper discountOrderDetailMapper;
    @Autowired
    private DiscountProductSingleDetailMapper discountProductSingleDetailMapper;
    @Autowired
    private DiscountProductSingleShareDetailMapper discountProductSingleShareDetailMapper;
    @Autowired
    private DiscountConditionPromotionDetailMapper discountConditionPromotionDetailMapper;
    @Autowired
    private PromotionEntityMapper promotionEntityMapper;
    @Autowired
    private DiscountProcesserService discountProcesserService;
    @Autowired
    private DiscountConditionGiftDetailMapper discountConditionGiftDetailMapper;
    @Autowired
    private PatchGrouponThemeEntityMapper patchGrouponThemeEntityMapper;
    @Autowired
    private PromotionMemberGradeMapper promotionMemberGradeMapper;
    @Autowired
    private BaseActivityMapper baseActivityMapper;
    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Override
    public Map<String, GoodsDetailModel> buildSingle(List<PromotionGoods> promotionGoodsList, FrontPromotionTypeEnum frontPromotionTypeEnum) {
        Map<String, GoodsDetailModel> goodsDetailModelMap = new HashMap<>();
        for(PromotionGoods promotionGoods : promotionGoodsList){
            GoodsDetailModel goodsDetailModel = buildGoodsDetailModel(promotionGoods, frontPromotionTypeEnum);
            goodsDetailModelMap.put(goodsDetailModel.getThirdSkuId(), goodsDetailModel);
        }
        return goodsDetailModelMap;
    }

    @Override
    public List<ConditionDiscountModel> buildCondition(Map<String, GoodsDetailModel> goodsDetailModelMap, Object request, FrontPromotionTypeEnum frontPromotionTypeEnum) {
        List<String> thirdSkuIds = new ArrayList<>();
        for(GoodsDetailModel goodsDetailModel : goodsDetailModelMap.values()){
            // 仅留下第四组的活动商品和未参加单品类的商品，原因是只有这两种情况的商品才能参与条件类型活动，比如拼团属于第5组，这样的商品肯定与其他条件类活动互斥了
            if(null == goodsDetailModel.getFrontPromotionTypeEnum() || goodsDetailModel.getFrontPromotionTypeEnum().getGroup().equals(4)){
                thirdSkuIds.add(goodsDetailModel.getThirdSkuId());
            }
        }
        // 针对第三组的活动商品进行迭代
        List<Integer> codeList = FrontPromotionTypeEnum.getCodesByGroup(3, frontPromotionTypeEnum);
        // 查出商品对应的所有第三组活动
        List<ConditionDiscountModel> conditionDiscountModelList = getConditionDiscountModels(goodsDetailModelMap, request, thirdSkuIds, codeList);
        // 查出商品对应的所有第二组活动
        List<ConditionDiscountModel> conditionDiscountModelList2 = buildConditionTwo(goodsDetailModelMap, request, frontPromotionTypeEnum);
        conditionDiscountModelList.addAll(conditionDiscountModelList2);
        return conditionDiscountModelList;
    }

    private List<ConditionDiscountModel> buildConditionTwo(Map<String, GoodsDetailModel> goodsDetailModelMap, Object request, FrontPromotionTypeEnum frontPromotionTypeEnum) {
        // 针对第二组的活动商品进行迭代
        List<Integer> codes = FrontPromotionTypeEnum.getCodesByGroup(2, frontPromotionTypeEnum);
        if(null == codes || codes.isEmpty()){
            return new ArrayList<>();
        }
        List<ConditionDiscountModel> conditionDiscountModelListResult = new ArrayList<>();
        List<String> thirdSkuIds = new ArrayList<>();
        for(GoodsDetailModel goodsDetailModel : goodsDetailModelMap.values()){
            // 仅留下第四组和第一组的活动商品和未参加单品类的商品
            if(null == goodsDetailModel.getFrontPromotionTypeEnum()
                    || goodsDetailModel.getFrontPromotionTypeEnum().getGroup().equals(4) || goodsDetailModel.getFrontPromotionTypeEnum().getGroup().equals(1)){
                thirdSkuIds.add(goodsDetailModel.getThirdSkuId());
            }
        }
        for (Integer code : codes){
            List<Integer> codeList = new ArrayList<>();
            codeList.add(code);
            List<ConditionDiscountModel> conditionDiscountModelList = getConditionDiscountModels(goodsDetailModelMap, request, thirdSkuIds, codeList);
            conditionDiscountModelListResult.addAll(conditionDiscountModelList);
        }
        return conditionDiscountModelListResult;
    }


    /** 按规则进行商品分组 */
    private List<ConditionDiscountModel> getConditionDiscountModels(Map<String, GoodsDetailModel> goodsDetailModelMap, Object request, List<String> thirdSkuIds, List<Integer> codeList) {
        if(null == thirdSkuIds || thirdSkuIds.isEmpty() || null == codeList || codeList.isEmpty()){
            return new ArrayList<>();
        }

        // 多品中的单品特殊处理，这里是针对两种类型的活动：单品X、组合，因为这两种活动不同于其它多品活动，他们实际上是属于单品类活动，这里把他们作为一种特殊的多品活动进行计算
        List<ConditionDiscountModel> speConditionDiscountModelList = new ArrayList<>();
        List<Integer> speCodeList = new ArrayList<>();
        if(codeList.contains(FrontPromotionTypeEnum.XOFFER_MAN_X_Y_ZE.getCode()) || codeList.contains(FrontPromotionTypeEnum.COMPLEX_X_JIAN_FU_Y.getCode())){
            speCodeList.add(FrontPromotionTypeEnum.XOFFER_MAN_X_Y_ZE.getCode());
            speCodeList.add(FrontPromotionTypeEnum.COMPLEX_X_JIAN_FU_Y.getCode());
            codeList.remove(FrontPromotionTypeEnum.XOFFER_MAN_X_Y_ZE.getCode());
            codeList.remove(FrontPromotionTypeEnum.COMPLEX_X_JIAN_FU_Y.getCode());
            for(int i = thirdSkuIds.size() - 1; i>=0; i--){
                List<String> speThirdSkuIds = new ArrayList<>();
                speThirdSkuIds.add(thirdSkuIds.get(i));
                // 活动主表数据
                List<PromotionEntity> promotionEntityList = promotionEntityMapper.findByThirdSkuIdsAndFrontPromotionTypeList(speThirdSkuIds, speCodeList);
                if(null != promotionEntityList && !promotionEntityList.isEmpty()){
                    PromotionEntity promotionEntity = promotionEntityList.get(0);
                    ConditionDiscountModel conditionDiscountModel = new ConditionDiscountModel();
                    conditionDiscountModel.setPromotionId(promotionEntity.getId().toString());
                    conditionDiscountModel.setPromotionCode(promotionEntity.getPromotionCode());
                    conditionDiscountModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(promotionEntity.getFrontPromType()));
                    conditionDiscountModel.setPromotionCreateTime(promotionEntity.getStartTime());
                    conditionDiscountModel.setOverlayAppFlag(promotionEntity.getOverlayAppFlag() == 1);
                    conditionDiscountModel.setOverlayAppNum(promotionEntity.getOverlayAppNum());
                    conditionDiscountModel.setThirdSkuIdList(speThirdSkuIds);
                    conditionDiscountModel.setParcelsFlag(promotionEntity.getParcelsFlag() == 1);
                    conditionDiscountModel.setChannelCodes(promotionEntity.getChannelCodes());
                    conditionDiscountModel.setMemTypes(promotionEntity.getMemTypes());
                    PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
                    promotionMemberGradeQ.setPromotionCode(conditionDiscountModel.getPromotionCode());
                    promotionMemberGradeQ.setDeleteFlag(false);
                    // 活动等级信息
                    List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
                    conditionDiscountModel.setPromotionMemberGradeList(promotionMemberGradeList);
                    AbstractConditionDiscountProcessor.ConditionResult conditionResult = discountProcesserService.getConditionProcessor(conditionDiscountModel.getFrontPromotionTypeEnum()).isCondition(conditionDiscountModel, goodsDetailModelMap, request, DiscountAmountServiceOperateEnum.COUPON_QUERY);
                    if(null != conditionResult && conditionResult.getPass()){
                        thirdSkuIds.remove(i);
                        speConditionDiscountModelList.add(conditionDiscountModel);
                    }
                }
            }

        }

        // 其它类型是组合活动
        List<PromotionEntity> promotionEntityList = promotionEntityMapper.findByThirdSkuIdsAndFrontPromotionTypeList(thirdSkuIds, codeList);
        List<ConditionDiscountModel> conditionDiscountModelList = new ArrayList<>();
        for(PromotionEntity promotionEntity : promotionEntityList){
            ConditionDiscountModel conditionDiscountModel = new ConditionDiscountModel();
            conditionDiscountModel.setPromotionId(promotionEntity.getId().toString());
            conditionDiscountModel.setPromotionCode(promotionEntity.getPromotionCode());
            conditionDiscountModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(promotionEntity.getFrontPromType()));
            conditionDiscountModel.setPromotionCreateTime(promotionEntity.getStartTime());
            conditionDiscountModel.setOverlayAppFlag(promotionEntity.getOverlayAppFlag() == 1);
            conditionDiscountModel.setOverlayAppNum(promotionEntity.getOverlayAppNum());
            List<String> skuIdList = promotionEntityMapper.findThirdSkuIdsBySkuIdsAndId(thirdSkuIds, promotionEntity.getId());
            conditionDiscountModel.setThirdSkuIdList(skuIdList);
            conditionDiscountModel.setParcelsFlag(promotionEntity.getParcelsFlag() == 1);
            conditionDiscountModel.setChannelCodes(promotionEntity.getChannelCodes());
            conditionDiscountModel.setMemTypes(promotionEntity.getMemTypes());
            PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
            promotionMemberGradeQ.setPromotionCode(conditionDiscountModel.getPromotionCode());
            promotionMemberGradeQ.setDeleteFlag(false);
            List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
            conditionDiscountModel.setPromotionMemberGradeList(promotionMemberGradeList);
            conditionDiscountModelList.add(conditionDiscountModel);
        }

        // 第一次循环，移除未生效的活动，预筛选
        for (int i = conditionDiscountModelList.size() - 1; i >= 0; i--) {
            ConditionDiscountModel conditionDiscountModel = conditionDiscountModelList.get(i);
            AbstractConditionDiscountProcessor.ConditionResult conditionResult = discountProcesserService.getConditionProcessor(conditionDiscountModel.getFrontPromotionTypeEnum()).isCondition(conditionDiscountModel, goodsDetailModelMap, request, DiscountAmountServiceOperateEnum.COUPON_QUERY);
            if(null == conditionResult || !conditionResult.getPass()){
                List<String> thirdSkuIdList = conditionDiscountModelList.get(i).getThirdSkuIdList();
                // 净化对应的商品模型，因为在预筛选的时候会产生垃圾数据
                if(null != thirdSkuIdList && !thirdSkuIdList.isEmpty()){
                    for(String thirdSkuId : thirdSkuIdList){
                        GoodsDetailModel goodsDetailModelOld = goodsDetailModelMap.get(thirdSkuId);
                        goodsDetailModelOld.setConditionValidNum(null);
                    }
                }
                conditionDiscountModelList.remove(i);
            }
        }

        // 循环移除对应的重复商品，也就是分组
        List<String> selectedThirdSkuIdList = new ArrayList();
        for (int i = 0; i < conditionDiscountModelList.size(); i++) {
            ConditionDiscountModel conditionDiscountModel = conditionDiscountModelList.get(i);
            List<String> thirdSkuIdList = conditionDiscountModel.getThirdSkuIdList();
            for (int j = thirdSkuIdList.size() - 1; j >= 0; j--) {
                if (selectedThirdSkuIdList.contains(thirdSkuIdList.get(j))) {
                    // 净化对应的商品模型，因为在预筛选的时候会产生垃圾数据
                    GoodsDetailModel goodsDetailModelOld = goodsDetailModelMap.get(thirdSkuIdList.get(j));
                    goodsDetailModelOld.setConditionValidNum(null);
                    thirdSkuIdList.remove(j);
                } else {
                    selectedThirdSkuIdList.add(thirdSkuIdList.get(j));
                }
            }
        }
        // 移除商品未空的模型
        for (int i = conditionDiscountModelList.size() -1 ; i>=0 ;i--) {
            if(null == conditionDiscountModelList.get(i).getThirdSkuIdList() || conditionDiscountModelList.get(i).getThirdSkuIdList().isEmpty()){
                conditionDiscountModelList.remove(i);
            }
        }
        conditionDiscountModelList.addAll(speConditionDiscountModelList);
        return conditionDiscountModelList;
    }

    @Override
    public Map<MutuallyExclusiveTypeEnum, List<ConditionDiscountModel>> buildCoupon(Map<String, GoodsDetailModel> goodsDetailModelMap, List<QueryCouponPersonResponse> couponInfoList) {
        Map<MutuallyExclusiveTypeEnum, List<ConditionDiscountModel>> mutuallyExclusiveTypeEnumListMap = new HashMap<>();
        if(null == couponInfoList || couponInfoList.isEmpty()){
            return mutuallyExclusiveTypeEnumListMap;
        }
        List<String> skuIdList = new ArrayList<>();
        goodsDetailModelMap.forEach((k, goodsDetail) -> {
            skuIdList.add(goodsDetail.getSkuId().toString());
        });
        List<ConditionDiscountModel> couponDiscountModelList = new ArrayList<>();
        for(QueryCouponPersonResponse couponInfo : couponInfoList){
            CouponDetail couponDetailQ = new CouponDetail();
            couponDetailQ.setCouponCode(couponInfo.getCouponCode());
            List<CouponDetail> couponDetailList = couponDetailMapper.query(couponDetailQ);
            if(null == couponDetailList || couponDetailList.isEmpty()){
                throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "优惠券编码错误" + couponInfo.getCouponCode());
            }
            CouponDetail couponDetail = couponDetailList.get(0);

            ConditionDiscountModel conditionDiscountModel = new ConditionDiscountModel();
            conditionDiscountModel.setPromotionId(couponDetail.getPromotionId());
            conditionDiscountModel.setPromotionCode(couponDetail.getPromotionId());
            conditionDiscountModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.COUPON_);
            conditionDiscountModel.setCouponInfo(couponInfo);
            BaseActivity baseActivity =  baseActivityMapper.queryByPromotionId(conditionDiscountModel.getPromotionCode());
            if(null != baseActivity){
                conditionDiscountModel.setPromotionCreateTime(baseActivity.getStartTime());
                conditionDiscountModel.setChannelCodes(baseActivity.getChannelCodes());
                conditionDiscountModel.setMemTypes(baseActivity.getMemTypes());
            }
            PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
            promotionMemberGradeQ.setPromotionCode(conditionDiscountModel.getPromotionCode());
            promotionMemberGradeQ.setDeleteFlag(false);
            List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
            conditionDiscountModel.setPromotionMemberGradeList(promotionMemberGradeList);
            List<String> skuIds = couponGoodsMapper.querySkuIdByPromotionIdAndSkuIds(couponDetail.getPromotionId(), skuIdList);
            if(null != skuIds && !skuIds.isEmpty()){
                List<String> thirdSkuIdList = new ArrayList<>();
                goodsDetailModelMap.forEach((k, goodsDetail) -> {
                    if(skuIds.contains(goodsDetail.getSkuId().toString())){
                        thirdSkuIdList.add(goodsDetail.getThirdSkuId());
                    }
                });
                conditionDiscountModel.setThirdSkuIdList(thirdSkuIdList);
                couponDiscountModelList.add(conditionDiscountModel);
            }
        }

        // 分组
        List<ConditionDiscountModel> couponDiscountModelList1 = new ArrayList<>();
        List<ConditionDiscountModel> couponDiscountModelList2 = new ArrayList<>();
        List<ConditionDiscountModel> couponDiscountModelList3 = new ArrayList<>();
        List<ConditionDiscountModel> couponDiscountModelList4 = new ArrayList<>();
        for(ConditionDiscountModel couponDiscountModel : couponDiscountModelList){
            if(couponDiscountModel.getCouponInfo().getAmountDeductType().equals(0) && couponDiscountModel.getCouponInfo().getCouponPlatform().equals(1)){//平台商品券
                couponDiscountModelList1.add(couponDiscountModel);
            }
            else if(couponDiscountModel.getCouponInfo().getAmountDeductType().equals(0) && couponDiscountModel.getCouponInfo().getCouponPlatform().equals(2)) {//店铺商品券
                couponDiscountModelList2.add(couponDiscountModel);
            }
            else if(couponDiscountModel.getCouponInfo().getAmountDeductType().equals(1)) {//运费券
                couponDiscountModelList3.add(couponDiscountModel);
            }
            else if(couponDiscountModel.getCouponInfo().getAmountDeductType().equals(2)) {//待金券
                couponDiscountModelList4.add(couponDiscountModel);
            }
        }
        mutuallyExclusiveTypeEnumListMap.put(MutuallyExclusiveTypeEnum.PLATFORM_COUPON_AMOUNT, couponDiscountModelList1);
        mutuallyExclusiveTypeEnumListMap.put(MutuallyExclusiveTypeEnum.STORE_COUPON_AMOUNT, couponDiscountModelList2);
        mutuallyExclusiveTypeEnumListMap.put(MutuallyExclusiveTypeEnum.COUPON_FREIGHT, couponDiscountModelList3);
        mutuallyExclusiveTypeEnumListMap.put(MutuallyExclusiveTypeEnum.COUPON_PROXY_AMOUNT, couponDiscountModelList4);
        return mutuallyExclusiveTypeEnumListMap;
    }

    @Override
    public void save(DiscountOrderModel discountOrderModel) {
        DiscountOrderDetail discountOrderDetail = new DiscountOrderDetail();
        BeanUtils.copyProperties(discountOrderModel, discountOrderDetail);
        discountOrderDetail.setDiscountOrderStatus(discountOrderModel.getDiscountOrderStatus().getCode());
        discountOrderDetail.setDeleteFlag(false);
        if(null != discountOrderDetail.getId() && !discountOrderDetail.getId().equals(0L)){
            discountOrderDetail.setUpdateTime(new Date());
            discountOrderDetailMapper.update(discountOrderDetail);
        }else {
            discountOrderDetail.setCreateTime(new Date());
            discountOrderDetailMapper.insert(discountOrderDetail);
        }
        // 单品类活动及商品保存
        Map<String, GoodsDetailModel> goodsDetailModelMap = discountOrderModel.getGoodsDetailModelMap();
        if(null != goodsDetailModelMap && !goodsDetailModelMap.isEmpty()){
            goodsDetailModelMap.forEach((thirdSkuId, goodsDetailModel) ->{
                DiscountProductSingleDetail discountConditionPromotionDetail = new DiscountProductSingleDetail();
                BeanUtils.copyProperties(goodsDetailModel, discountConditionPromotionDetail);
                discountConditionPromotionDetail.setOrderNo(discountOrderModel.getOrderNo());
                if(null != goodsDetailModel.getFrontPromotionTypeEnum()){
                    discountConditionPromotionDetail.setFrontPromType(goodsDetailModel.getFrontPromotionTypeEnum().getCode());
                    discountConditionPromotionDetail.setPromType(goodsDetailModel.getFrontPromotionTypeEnum().getPromType().getCode());
                }
                if(null != goodsDetailModel.getConditionDiscountDetailStatus()){
                    discountConditionPromotionDetail.setConditionDiscountDetailStatus(goodsDetailModel.getConditionDiscountDetailStatus().getCode());
                }if(null != goodsDetailModel.getDiscountDetailStatusEnum()){
                    discountConditionPromotionDetail.setSingleDiscountDetailStatus(goodsDetailModel.getDiscountDetailStatusEnum().getCode());
                }if(null != goodsDetailModel.getCouponPlatAmountDiscountDetailStatus()){
                    discountConditionPromotionDetail.setCouponPlatAmountDiscountDetailStatus(goodsDetailModel.getCouponPlatAmountDiscountDetailStatus().getCode());
                }if(null != goodsDetailModel.getCouponStoreAmountDiscountDetailStatus()){
                    discountConditionPromotionDetail.setCouponStoreAmountDiscountDetailStatus(goodsDetailModel.getCouponStoreAmountDiscountDetailStatus().getCode());
                }if(null != goodsDetailModel.getCouponProxyAmountDiscountDetailStatus()){
                    discountConditionPromotionDetail.setCouponProxyAmountDiscountDetailStatus(goodsDetailModel.getCouponProxyAmountDiscountDetailStatus().getCode());
                }if(null != goodsDetailModel.getCouponFreightDiscountDetailStatus()){
                    discountConditionPromotionDetail.setCouponFreightAmountDiscountDetailStatus(goodsDetailModel.getCouponFreightDiscountDetailStatus().getCode());
                }
                if(null != discountConditionPromotionDetail.getId() && !discountConditionPromotionDetail.getId().equals(0L)){
                    discountConditionPromotionDetail.setUpdateTime(new Date());
                    discountProductSingleDetailMapper.update(discountConditionPromotionDetail);
                }else {
                    discountConditionPromotionDetail.setCreateTime(new Date());
                    discountConditionPromotionDetail.setDeleteFlag(false);
                   discountProductSingleDetailMapper.insert(discountConditionPromotionDetail);
                }
                // 共享活动
                Map<FrontPromotionTypeEnum, ShareModel> shareModelMap = goodsDetailModel.getShareModelMap();
                if(null != shareModelMap && !shareModelMap.isEmpty()){
                    shareModelMap.forEach((type,shareModel)->{
                        DiscountProductSingleShareDetail discountProductSingleShareDetail = new DiscountProductSingleShareDetail();
                        discountProductSingleShareDetail.setId(shareModel.getId());
                        discountProductSingleShareDetail.setOrderNo(discountOrderModel.getOrderNo());
                        discountProductSingleShareDetail.setSkuId(goodsDetailModel.getSkuId());
                        discountProductSingleShareDetail.setThirdSkuId(goodsDetailModel.getThirdSkuId());
                        discountProductSingleShareDetail.setPromotionSerialNo(shareModel.getPromotionSerialNo());
                        discountProductSingleShareDetail.setFrontPromType(shareModel.getFrontPromotionTypeEnum().getCode());
                        discountProductSingleShareDetail.setPromType(shareModel.getFrontPromotionTypeEnum().getPromType().getCode());
                        discountProductSingleShareDetail.setConditionDiscountDetailStatus(shareModel.getConditionDiscountDetailStatus().getCode());
                        if(null != shareModel.getId() && !shareModel.getId().equals(0L)){
                            discountProductSingleShareDetail.setUpdateTime(new Date());
                            discountProductSingleShareDetailMapper.update(discountProductSingleShareDetail);
                        }else {
                            discountProductSingleShareDetail.setCreateTime(new Date());
                            discountProductSingleShareDetail.setDeleteFlag(false);
                            discountProductSingleShareDetailMapper.insert(discountProductSingleShareDetail);
                        }
                    });
                }
            });
        }
        // 条件类活动及商品保存
        List<ConditionDiscountModel> conditionDiscountModelList = discountOrderModel.getConditionDiscountModelList();
        if(null != conditionDiscountModelList && !conditionDiscountModelList.isEmpty()){
            conditionDiscountModelList.forEach(conditionDiscountModel -> {
                DiscountConditionPromotionDetail discountConditionPromotionDetail = new DiscountConditionPromotionDetail();
                BeanUtils.copyProperties(conditionDiscountModel, discountConditionPromotionDetail);
                if(null != conditionDiscountModel.getDiscountDetailStatusEnum()){
                    discountConditionPromotionDetail.setDiscountDetailStatus(conditionDiscountModel.getDiscountDetailStatusEnum().getCode());
                }
                discountConditionPromotionDetail.setOrderNo(discountOrderModel.getOrderNo());
                if(null != conditionDiscountModel.getFrontPromotionTypeEnum()) {
                    discountConditionPromotionDetail.setPromType(conditionDiscountModel.getFrontPromotionTypeEnum().getPromType().getCode());
                    discountConditionPromotionDetail.setFrontPromType(conditionDiscountModel.getFrontPromotionTypeEnum().getCode());
                }
                if(null != conditionDiscountModel.getCouponInfo()){
                    discountConditionPromotionDetail.setCouponCode(conditionDiscountModel.getCouponInfo().getCouponCode());
                    discountConditionPromotionDetail.setAmountDeductType(conditionDiscountModel.getCouponInfo().getAmountDeductType());
                    discountConditionPromotionDetail.setCouponPlatform(conditionDiscountModel.getCouponInfo().getCouponPlatform());
                }
                if(null != discountConditionPromotionDetail.getId() && !discountConditionPromotionDetail.getId().equals(0L)){
                    discountConditionPromotionDetail.setUpdateTime(new Date());
                    discountConditionPromotionDetailMapper.update(discountConditionPromotionDetail);
                }else {
                    discountConditionPromotionDetail.setCreateTime(new Date());
                    discountConditionPromotionDetail.setDeleteFlag(false);
                    List<String> thirdSkuIdList = conditionDiscountModel.getThirdSkuIdList();
                    if(null != thirdSkuIdList && !thirdSkuIdList.isEmpty()){
                        String thirdSkuIdListStr = StringUtils.join(thirdSkuIdList, ",");
                        discountConditionPromotionDetail.setThirdSkuIdList(thirdSkuIdListStr);
                    }
                    discountConditionPromotionDetailMapper.insert(discountConditionPromotionDetail);
                }
                // 赠品
                List<GiftDetail> giftDetailList = conditionDiscountModel.getGiftDetailList();
                if(null != giftDetailList && !giftDetailList.isEmpty()){
                    giftDetailList.forEach(giftDetail -> {
                        DiscountConditionGiftDetail giftDetailDo = new DiscountConditionGiftDetail();
                        giftDetailDo.setId(giftDetail.getId());
                        giftDetailDo.setOrderNo(discountOrderModel.getOrderNo());
                        giftDetailDo.setPromotionSerialNo(conditionDiscountModel.getPromotionSerialNo());
                        giftDetailDo.setCouponPromotionId(giftDetail.getCouponPromotionId());
                        List<String> couponCodeList = giftDetail.getCouponCodeList();
                        if(null != couponCodeList && !couponCodeList.isEmpty()){
                            giftDetailDo.setCouponCodeList( StringUtils.join(couponCodeList, ","));
                        }
                        giftDetailDo.setThirdSkuId(giftDetail.getThirdProductCode());
                        giftDetailDo.setNum(giftDetail.getNum());
                        giftDetailDo.setGiftType(giftDetail.getGiftType());
                        giftDetailDo.setDeleteFlag(false);
                        if(null != giftDetailDo.getId() && !giftDetail.getId().equals(0L)){
                            giftDetailDo.setUpdateTime(new Date());
                            discountConditionGiftDetailMapper.update(giftDetailDo);
                        }else {
                            giftDetailDo.setCreateTime(new Date());
                            discountConditionGiftDetailMapper.insert(giftDetailDo);
                        }
                    });
                }

            });
        }
    }

    @Override
    public DiscountOrderModel load(String orderNo) {
        DiscountOrderDetail discountOrderDetailQ = new DiscountOrderDetail();
        discountOrderDetailQ.setOrderNo(orderNo);
        List<DiscountOrderDetail> discountOrderDetailList = discountOrderDetailMapper.query(discountOrderDetailQ);
        if(null != discountOrderDetailList && !discountOrderDetailList.isEmpty()){
            DiscountOrderDetail discountOrderDetail = discountOrderDetailList.get(0);
            DiscountOrderModel discountOrderModel = new DiscountOrderModel();
            BeanUtils.copyProperties(discountOrderDetail, discountOrderModel);
            discountOrderModel.setDiscountOrderStatus(DiscountOrderStatusEnum.getByCode(discountOrderDetail.getDiscountOrderStatus()));
            DiscountProductSingleDetail discountProductSingleDetailQ = new DiscountProductSingleDetail();
            discountProductSingleDetailQ.setOrderNo(orderNo);
            List<DiscountProductSingleDetail> discountProductSingleDetailList = discountProductSingleDetailMapper.query(discountProductSingleDetailQ);
            if(null != discountOrderDetailList && !discountOrderDetailList.isEmpty()){
                Map<String, GoodsDetailModel> goodsDetailModelMap = new HashMap<>();
                for(DiscountProductSingleDetail discountProductSingleDetail : discountProductSingleDetailList){
                    GoodsDetailModel goodsDetailModel = new GoodsDetailModel();
                    BeanUtils.copyProperties(discountProductSingleDetail, goodsDetailModel);
                    if(null != discountProductSingleDetail.getFrontPromType()){
                        goodsDetailModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(discountProductSingleDetail.getFrontPromType()));
                    }
                    if(null != discountProductSingleDetail.getConditionDiscountDetailStatus()){
                        goodsDetailModel.setConditionDiscountDetailStatus(DiscountDetailStatusEnum.getByCode(discountProductSingleDetail.getConditionDiscountDetailStatus()));
                    }else if(null != discountProductSingleDetail.getSingleDiscountDetailStatus()){
                        goodsDetailModel.setDiscountDetailStatusEnum(DiscountDetailStatusEnum.getByCode(discountProductSingleDetail.getSingleDiscountDetailStatus()));
                    }else if(null != discountProductSingleDetail.getCouponPlatAmountDiscountDetailStatus()){
                        goodsDetailModel.setCouponPlatAmountDiscountDetailStatus(DiscountDetailStatusEnum.getByCode(discountProductSingleDetail.getCouponPlatAmountDiscountDetailStatus()));
                    }else if(null != discountProductSingleDetail.getCouponStoreAmountDiscountDetailStatus()){
                        goodsDetailModel.setCouponStoreAmountDiscountDetailStatus(DiscountDetailStatusEnum.getByCode(discountProductSingleDetail.getCouponStoreAmountDiscountDetailStatus()));
                    }else if(null != discountProductSingleDetail.getCouponProxyAmountDiscountDetailStatus()){
                        goodsDetailModel.setCouponProxyAmountDiscountDetailStatus(DiscountDetailStatusEnum.getByCode(discountProductSingleDetail.getCouponProxyAmountDiscountDetailStatus()));
                    }else if(null != discountProductSingleDetail.getCouponFreightAmountDiscountDetailStatus()){
                        goodsDetailModel.setCouponFreightDiscountDetailStatus(DiscountDetailStatusEnum.getByCode(discountProductSingleDetail.getCouponFreightAmountDiscountDetailStatus()));
                    }
                    goodsDetailModelMap.put(goodsDetailModel.getThirdSkuId(), goodsDetailModel);
                }
                discountOrderModel.setGoodsDetailModelMap(goodsDetailModelMap);
            }

            DiscountConditionPromotionDetail discountConditionPromotionDetailQ = new DiscountConditionPromotionDetail();
            discountConditionPromotionDetailQ.setOrderNo(orderNo);
            List<DiscountConditionPromotionDetail> discountConditionPromotionDetailList = discountConditionPromotionDetailMapper.query(discountConditionPromotionDetailQ);
            if(null != discountConditionPromotionDetailList && !discountConditionPromotionDetailList.isEmpty()){
                List<ConditionDiscountModel> conditionDiscountModelList = new ArrayList<>();
                for(DiscountConditionPromotionDetail discountConditionPromotionDetail : discountConditionPromotionDetailList){
                    ConditionDiscountModel conditionDiscountModel = new ConditionDiscountModel();
                    BeanUtils.copyProperties(discountConditionPromotionDetail, conditionDiscountModel);
                    conditionDiscountModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(discountConditionPromotionDetail.getFrontPromType()));
                    conditionDiscountModel.setDiscountDetailStatusEnum(DiscountDetailStatusEnum.getByCode(discountConditionPromotionDetail.getDiscountDetailStatus()));
                    if(null != discountConditionPromotionDetail.getCouponCode()){
                        QueryCouponPersonResponse couponInfo = new QueryCouponPersonResponse();
                        BeanUtils.copyProperties(discountConditionPromotionDetail, couponInfo);
                        conditionDiscountModel.setCouponInfo(couponInfo);
                    }
                    String thirdSkuIdListStr = discountConditionPromotionDetail.getThirdSkuIdList();
                    if(null != thirdSkuIdListStr && !thirdSkuIdListStr.isEmpty()){
                        List<String> thirdSkuIdList = Arrays.asList(thirdSkuIdListStr.split(","));
                        conditionDiscountModel.setThirdSkuIdList(thirdSkuIdList);
                        if(null != thirdSkuIdList && !thirdSkuIdList.isEmpty()){
                            for(String thirdSkuId : thirdSkuIdList){
                                //共享类的活动
                                DiscountProductSingleShareDetail discountProductSingleShareDetailQ = new DiscountProductSingleShareDetail();
                                discountProductSingleShareDetailQ.setOrderNo(orderNo);
                                discountProductSingleShareDetailQ.setThirdSkuId(thirdSkuId);
                                discountProductSingleShareDetailQ.setPromotionSerialNo(discountConditionPromotionDetail.getPromotionSerialNo());
                                List<DiscountProductSingleShareDetail> discountProductSingleShareDetailList = discountProductSingleShareDetailMapper.query(discountProductSingleShareDetailQ);
                                if(null != discountProductSingleShareDetailList && !discountProductSingleShareDetailList.isEmpty()){
                                    Map<FrontPromotionTypeEnum, ShareModel> shareModelMap = new HashMap<>();
                                    for(DiscountProductSingleShareDetail discountProductSingleShareDetail : discountProductSingleShareDetailList){
                                        ShareModel shareModel = new ShareModel();
                                        shareModel.setId(discountProductSingleShareDetail.getId());
                                        shareModel.setPromotionSerialNo(discountProductSingleShareDetail.getPromotionSerialNo());
                                        shareModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(discountProductSingleShareDetail.getFrontPromType()));
                                        shareModel.setConditionDiscountDetailStatus(DiscountDetailStatusEnum.getByCode(discountProductSingleShareDetail.getConditionDiscountDetailStatus()));
                                        shareModelMap.put(shareModel.getFrontPromotionTypeEnum(), shareModel);
                                    }
                                    GoodsDetailModel goodsDetailModel = discountOrderModel.getGoodsDetailModelMap().get(thirdSkuId);
                                    goodsDetailModel.setShareModelMap(shareModelMap);
                                }
                            }
                        }
                    }
                    // 赠品
                    DiscountConditionGiftDetail giftDetailQ = new DiscountConditionGiftDetail();
                    giftDetailQ.setOrderNo(orderNo);
                    giftDetailQ.setPromotionSerialNo(conditionDiscountModel.getPromotionSerialNo());
                    List<DiscountConditionGiftDetail> conditionGiftDetailList = discountConditionGiftDetailMapper.query(giftDetailQ);
                    if(null != conditionGiftDetailList && !conditionGiftDetailList.isEmpty()){
                        List<GiftDetail> giftDetailList = new ArrayList<>();
                        for(DiscountConditionGiftDetail discountConditionGiftDetail : conditionGiftDetailList){
                            GiftDetail giftDetail = new GiftDetail();
                            giftDetail.setId(discountConditionGiftDetail.getId());
                            giftDetail.setGiftType(discountConditionGiftDetail.getGiftType());
                            giftDetail.setNum(discountConditionGiftDetail.getNum());
                            if(null != discountConditionGiftDetail.getCouponCodeList()){
                                List<String> couponCodeList = Arrays.asList(discountConditionGiftDetail.getCouponCodeList().split(","));
                                giftDetail.setCouponCodeList(couponCodeList);
                            }
                            giftDetail.setCouponPromotionId(discountConditionGiftDetail.getCouponPromotionId());
                            giftDetail.setThirdProductCode(discountConditionGiftDetail.getThirdSkuId());
                            giftDetailList.add(giftDetail);
                        }
                        conditionDiscountModel.setGiftDetailList(giftDetailList);
                    }
                    conditionDiscountModelList.add(conditionDiscountModel);
                }
                discountOrderModel.setConditionDiscountModelList(conditionDiscountModelList);
            }
            return discountOrderModel;
        }
        return null;
    }

    @Override
    public DiscountOrderModel buildDiscountOrderModel(DiscountSubOrderRequest discountSubOrderRequest) {
        // 把每个子订单的模型都加载好
        if(null != discountSubOrderRequest){
            DiscountOrderModel discountOrderModel = new DiscountOrderModel();
            discountOrderModel.setOrderNo(discountSubOrderRequest.getOrderNo());
            if(null != discountSubOrderRequest.getConditionDiscountRequestList() && !discountSubOrderRequest.getConditionDiscountRequestList().isEmpty()){
                List<ConditionDiscountModel> conditionDiscountModelList = new ArrayList<>();
                for(ConditionDiscountRequest conditionDiscountRequest : discountSubOrderRequest.getConditionDiscountRequestList()){
                    ConditionDiscountModel conditionDiscountModel = new ConditionDiscountModel();
                    BeanUtils.copyProperties(conditionDiscountRequest, conditionDiscountModel);
                    conditionDiscountModel.setThirdSkuIdList(conditionDiscountRequest.getThirdSkuIdList());
                    conditionDiscountModel.setCouponInfo(conditionDiscountModel.getCouponInfo());
                    conditionDiscountModel.setGiftDetailList(conditionDiscountRequest.getGiftDetailList());
                    conditionDiscountModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(conditionDiscountRequest.getFrontPromotionType()));
                    conditionDiscountModelList.add(conditionDiscountModel);
                }
                discountOrderModel.setConditionDiscountModelList(conditionDiscountModelList);
            }
            if(null != discountSubOrderRequest.getGoodsDetailRequestList() && !discountSubOrderRequest.getGoodsDetailRequestList().isEmpty()){
                Map<String, GoodsDetailModel> goodsDetailModelMap = new HashMap<>();
                for(GoodsDetailRequest goodsDetailRequest : discountSubOrderRequest.getGoodsDetailRequestList()){
                    GoodsDetailModel goodsDetailModel = new GoodsDetailModel();
                    BeanUtils.copyProperties(goodsDetailRequest, goodsDetailModel);
                    if(null != goodsDetailRequest.getFrontPromotionType() && !goodsDetailRequest.getFrontPromotionType().equals(0)){
                        goodsDetailModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(goodsDetailRequest.getFrontPromotionType()));
                    }
                    if(StringUtils.isBlank(goodsDetailModel.getPromotionCode())){
                        goodsDetailModel.setPromotionCode(null);
                    }else {
                        PromotionEntity promotionEntity = promotionEntityMapper.queryByPromotionCode(goodsDetailModel.getPromotionCode());
                        if(null != promotionEntity){
                            goodsDetailModel.setPromotionId(promotionEntity.getId().toString());
                        }else {
                            goodsDetailModel.setPromotionId(goodsDetailModel.getPromotionCode());
                        }
                    }
                    List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                        setGoodsCode(goodsDetailModel.getThirdSkuId());
                    }});
                    if(null == productStoreInfos || productStoreInfos.isEmpty()){
                        throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "商品" + goodsDetailModel.getThirdSkuId() + "不存在");
                    }
                    goodsDetailModel.setSkuId(productStoreInfos.get(0).getId());
                    if(StringUtils.isBlank(goodsDetailModel.getGrouponInstCode())){
                        goodsDetailModel.setGrouponInstCode(null);
                    }
                    goodsDetailModelMap.put(goodsDetailModel.getThirdSkuId(), goodsDetailModel);
                }
                discountOrderModel.setGoodsDetailModelMap(goodsDetailModelMap);
            }
            return discountOrderModel;
        }
        return null;
    }

    private GoodsDetailModel buildGoodsDetailModel(PromotionGoods promotionGoods, FrontPromotionTypeEnum frontPromotionTypeEnum) {
        // 查询商品的基本信息
        List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
            setGoodsCode(promotionGoods.getThirdProductCode());
        }});
        if(null == productStoreInfos || productStoreInfos.isEmpty()){
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, promotionGoods.getThirdProductCode() + "商品不存在");
        }
        if(productStoreInfos.size() >= 2){
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, promotionGoods.getThirdProductCode() + "该商品数据库有多个");
        }
        ProductStoreInfo goodsSku = productStoreInfos.get(0);
        GoodsDetailModel goodsDetailModel = new GoodsDetailModel();
        goodsDetailModel.setSkuId(goodsSku.getId());
        goodsDetailModel.setNum(promotionGoods.getNum());
        goodsDetailModel.setSalePrice(goodsSku.getSalePriceWithTax());
        goodsDetailModel.setThirdSkuId(promotionGoods.getThirdProductCode());
        goodsDetailModel.setTotalAmount(Money.multiply(goodsSku.getSalePriceWithTax(),new BigDecimal(promotionGoods.getNum())));
        goodsDetailModel.setLogisticsFee(promotionGoods.getLogisticsFee());
        // 拼团活动的主要参数
        String grouponPromotionCode = promotionGoods.getGrouponPromotionCode();
        if(null != grouponPromotionCode && !"".equals(grouponPromotionCode)){
            PatchGrouponThemeEntity patchGrouponThemeEntityQ = new PatchGrouponThemeEntity();
            patchGrouponThemeEntityQ.setDeleteFlag(0);
            patchGrouponThemeEntityQ.setGroupCode(grouponPromotionCode);
            PatchGrouponThemeEntity patchGrouponThemeEntity = patchGrouponThemeEntityMapper.query(patchGrouponThemeEntityQ);
            if(null == patchGrouponThemeEntity){
                throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "未查询到此拼团活动" + grouponPromotionCode);
            }
            goodsDetailModel.setPromotionId(patchGrouponThemeEntity.getId().toString());
            goodsDetailModel.setPromotionCode(patchGrouponThemeEntity.getGroupCode());
            goodsDetailModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(patchGrouponThemeEntity.getFrontPromType()));
            goodsDetailModel.setPromotionCreateTime(patchGrouponThemeEntity.getCreateTime());
            goodsDetailModel.setGrouponInstCode(promotionGoods.getGrouponInstCode());
            goodsDetailModel.setLaunchFlag(promotionGoods.getLaunchFlag());
            goodsDetailModel.setChannelCodes(patchGrouponThemeEntity.getChannelCodes());
            goodsDetailModel.setMemTypes(patchGrouponThemeEntity.getMemTypes());
        }else {
            // 单品类活动参数完善
            List<Integer> singleCodes = FrontPromotionTypeEnum.getExclusiveSingleCodes(1, frontPromotionTypeEnum);
            List<String> thirdSkuIdQs = new ArrayList<>();
            thirdSkuIdQs.add(goodsDetailModel.getThirdSkuId());
            if (null != singleCodes && !singleCodes.isEmpty()) {
                List<PromotionEntity> promotionEntityList = promotionEntityMapper.findByThirdSkuIdsAndFrontPromotionTypeList(thirdSkuIdQs, singleCodes);
                if (null != promotionEntityList && !promotionEntityList.isEmpty()) {
                    PromotionEntity promotionEntity = promotionEntityList.get(0);
                    goodsDetailModel.setPromotionId(promotionEntity.getId().toString());
                    goodsDetailModel.setPromotionCode(promotionEntity.getPromotionCode());
                    goodsDetailModel.setFrontPromotionTypeEnum(FrontPromotionTypeEnum.getByCode(promotionEntity.getFrontPromType()));
                    goodsDetailModel.setPromotionCreateTime(promotionEntity.getCreateTime());
                    goodsDetailModel.setOverlayAppFlag(promotionEntity.getOverlayAppFlag() == 1);
                    goodsDetailModel.setOverlayAppNum(promotionEntity.getOverlayAppNum());
                    goodsDetailModel.setParcelsFlag(promotionEntity.getParcelsFlag() == 1);
                    goodsDetailModel.setChannelCodes(promotionEntity.getChannelCodes());
                    goodsDetailModel.setMemTypes(promotionEntity.getMemTypes());
                }
            }
        }
        // 会员等级基础参数
        PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
        promotionMemberGradeQ.setPromotionCode(goodsDetailModel.getPromotionCode());
        promotionMemberGradeQ.setDeleteFlag(false);
        List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
        goodsDetailModel.setPromotionMemberGradeList(promotionMemberGradeList);
        return goodsDetailModel;
    }


}
